package com.ruoyi.common.config.jackson;

import com.baomidou.mybatisplus.annotation.IEnum;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;

import java.beans.PropertyDescriptor;
import java.io.IOException;

/**
 * @Classname BaseEnumDeserializer
 * @Author: sunluquan
 * @Date: 2022/1/5 08:44
 * @Description TODO
 * 自定义{@link IEnum}枚举统一接口反序列化
 */
public class IEnumDeserializer extends JsonDeserializer<IEnum> {

    @Override
    public IEnum deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        String value = p.getValueAsString();

        if(StringUtils.isNotEmpty(value)){
            PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptorMap(p.getCurrentValue()).get(p.getCurrentName());
            Class<IEnum> iEnumClass = (Class<IEnum>) propertyDescriptor.getPropertyType();

            IEnum[] enumConstants = iEnumClass.getEnumConstants();
            for (IEnum enumConstant : enumConstants) {
                if(value.equals(enumConstant.getValue().toString())){
                    return enumConstant;
                }
            }
        }
        return null;
    }
}
